package pct.account;

import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import pct.database.PcServiceImpl;
import pct.entity.User;
import pct.manage.StatusManager;
import pct.page.PageFilter;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

@SuppressWarnings({ "serial", "rawtypes" })
public class Register extends ActionSupport implements ModelDriven, Preparable,
		SessionAware {
	private User user = new User();
	private String passwordCon;
	private PcServiceImpl pcService = new PcServiceImpl();
	private Map<String, Object> session;

	public String execute() {
		// a StatusManager instance is created and bounded to the new registered user
		StatusManager sm = new StatusManager();
		pcService.addUser(user);
		sm.setCurrentUser(user);
		PageFilter pf = new PageFilter();
		sm.setRelatedGroups(pf.getFirstPageGroups(user));
		sm.setCurrentPage(1);
		sm.setPageType(1);
		session.put("status", sm);
		return SUCCESS;
	}

	@Override
	public Object getModel() {
		return user;
	}

	@Override
	public void prepare() throws Exception {
		pcService.connectDB();
	}

	public void validate() {
		if (user.getPassword().length() == 0) {
			addFieldError("password", getText("password.required"));
		} else if (user.getUsername().length() == 0) {
			addFieldError("username", getText("username.required"));
		} else if (passwordCon.length() == 0) {
			addFieldError("passwordConfirm",
					getText("confirmedPassword.required"));
		} else if (!user.getPassword().equals(passwordCon)) {
			addFieldError("passwordCon", getText("password.inconsistency"));
		} else if (pcService.userExists(user)) {
			addFieldError("username", getText("username.duplicated"));
		} else if (user.getQuestion().length() == 0) {
			addFieldError("question", getText("question.required"));
		} else if (user.getAnswer().length() == 0) {
			addFieldError("answer", getText("answer.required"));
		} else if (user.getUsername().equals("visitor")) {
			// reserved username for anonymous visitor
			addFieldError("username", getText("username.duplicated"));
		}
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public String getPasswordCon() {
		return passwordCon;
	}

	public void setPasswordCon(String passwordCon) {
		this.passwordCon = passwordCon;
	}
}
